import { Inject, Injectable } from '@nestjs/common'
import { ClientProxy } from '@nestjs/microservices'
import { firstValueFrom } from 'rxjs'
import { BOT_CLIENT, BOT_CLIENT_GET_GUILD, BOT_CLIENT_GET_MEMBER, BOT_CLIENT_GET_USER } from './bot-client.constants'
import { CacheGuildDto } from './dto/cache-guild.dto'
import { CacheUserDto } from './dto/cache-user.dto'
import { GetCacheUserDto } from './dto/get-cache-uesr.dto'
import { GetGuildDto } from './dto/get-guild.dto'
import { CacheMemberDto } from '@boticord/bot-client/dto/cache-member.dto'
import { GetCacheMemberDto } from '@boticord/bot-client/dto/get-cache-member.dto'

@Injectable()
export class BotClientService {
  constructor(
    @Inject(BOT_CLIENT) private readonly bot: ClientProxy,
  ) {}

  async getUser(userID: string): Promise<CacheUserDto | null> {
    try {
      return await firstValueFrom(
        this.bot.send<CacheUserDto, GetCacheUserDto>(BOT_CLIENT_GET_USER, { userID }),
      )
    } catch {
      return null
    }
  }

  async getGuild(guildID: string): Promise<CacheGuildDto | null> {
    try {
      return await firstValueFrom(
        this.bot.send<CacheGuildDto, GetGuildDto>(BOT_CLIENT_GET_GUILD, { guildID }),
      )
    } catch {
      return null
    }
  }

  async getMember(guildID: string, userID: string): Promise<CacheMemberDto | null> {
    try {
      return await firstValueFrom(
        this.bot.send<CacheMemberDto, GetCacheMemberDto>(BOT_CLIENT_GET_MEMBER, { guildID, userID }),
      )
    } catch {
      return null
    }
  }
}
